package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.sky.constant.MessageConstant;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.BaseException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.UserDishMapper;
import com.sky.service.UserDishService;
import com.sky.vo.DishItemVO;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author zcf
 */
@Service
@Slf4j
public class UserDishServiceImpl implements UserDishService {

    @Resource
    private UserDishMapper userDishMapper;

    @Resource
    private DishFlavorMapper dishFlavorMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<DishVO> list(Long categoryId) {
        //先从redis中获取数据
       //判断redis中是否有缓存
        String key="dish:cache:"+categoryId;
        //取出集合
        String json = stringRedisTemplate.opsForValue().get(key);
        //将json转为集合
        if (StringUtils.isNotEmpty(json)) {
            log.info("从redis中获取数据");
            return JSON.parseArray(json, DishVO.class);
        }
        List<DishVO> list = new ArrayList<>();
        log.info("从数据库中获取数据");
        List<Dish> dishList = userDishMapper.list(categoryId);
        if (dishList == null && dishList.size() == 0) {
            throw new BaseException(MessageConstant.QUERY_DISH_FAILED);
        }
        dishList.forEach(
                dish -> {
                    DishVO dishVO = new DishVO();
                    BeanUtils.copyProperties(dish, dishVO);
                    list.add(dishVO);
                }
        );
        list.forEach(
                dishVO -> {
                    List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(dishVO.getId());
                    dishVO.setFlavors(dishFlavors);
                }
        );
        //将集合保存到redis中
        log.info("将数据保存到redis中");
        stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(list));
        return list;
    }
}
